<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
<title>Zookeeper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" rel="stylesheet"
	href="widgets/xloadtree/xtree.css" />
<script type="text/javascript" src="widgets/xloadtree/xtree.js"></script>
<script type="text/javascript" src="widgets/xloadtree/xmlextras.js"></script>
<script type="text/javascript" src="widgets/xloadtree/xloadtree.js"></script>
<script
	src="http://libs.baidu.com/mootools/1.4.5/mootools-yui-compressed.js"></script>
<style type="text/css">
body {
	background: white;
	color: black;
}
#popupMenu a{
	font-size:14px;
}
.popupMenu {
	position: absolute;
	left: 400px;
	top: 150px;
	min-width:10px;
	max-width:300px;
	width:auto;
	height:auto;
	z-index:100;
	
    border:3px #EBEBEB solid;
    background-color:#fff;
}

.dtable{
	border:3px #EBEBEB solid;
	clear:both;
	width:100%;
	min-height:100px;
}

.dtable dl{
	clear:both;
	display:block;
	height:30px;
}

.dtable dt,dd{
	margin:5px;
	float: left;
}
.button{
	cursor:pointer;
	font-size:20px;
}
</style>

<script>

//override xtree function
function _startLoadXmlTree(sSrc, jsNode) {
	if (jsNode.loading || jsNode.loaded)
		return;
	jsNode.loading = true;
	var xmlHttp = XmlHttp.create();
	xmlHttp.open("GET", sSrc, true);	// async
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			var oXmlDoc = xmlHttp.responseXML;
			var root = oXmlDoc.documentElement;
			if(root.tagName=='error'){
				alert(root.getAttribute("msg"));
				return;
			}
			_xmlFileLoaded(oXmlDoc, jsNode);
		}
	};
	// call in new thread to allow ui to update
	window.setTimeout(function () {
		xmlHttp.send(null);
	}, 10);
}

function sendHttpRequest(url, params, callback, method, cache){
	var myRequest = new Request({
		url:url, method:method||'get',
		onSuccess: function(responseText, responseXML){
			if(callback){
				callback(true, responseText);
			}
		},
		onFailure: function(req){
			if(callback){
				callback(false, req);
			}
		},
		onException: function(headerName, value){
			if(callback){
				callback(false, headerName+'='+value);
			}
		}
	});
	if(!cache){
		params['_'] = ((new Date()).getTime());
	}
	myRequest.send({'data':params});
}

function ajaxRequest(url, values, callback){
	var interceptor=function(success, responseText){
		var result = eval("("+responseText+")");
		if(!success){
			alert('网络请求错误！');
		}else if(result.code=='0000'){
			callback(result.data);
		}else{
			alert(result.error);
		}
	}
	sendHttpRequest(url, values, interceptor);
}

/////////////////////////////////

window.addEvent('domready', function() {
	///////////////////////////////////////////////////
	document.oncontextmenu = function (){return false;}
	
	document.onmousedown1 = function(e){
	    var menu = $('popupMenu');
	    var target = e.target||e.srcElement;
	    if(e.button==2){
	        menu.setAttribute('class','popupMenu');
	        menu.style.display = '';
	        menu.style.top = (e.clientY+'px');
	        menu.style.left = (e.clientX+'px');
	       	
	    }else{
	        if(target!=menu && target.parentNode!=menu){
	        	menu.style.display = 'none';
	        }
	    }
	};
});

////////////////////////////////////////

var URLPREFIX = "/zkmanager/zk";
var ROOT = '/';
var currentUrl = null;

function showOopupMenu(target){
	var id = target.id;
	var sa = id.split('-',4);
	var itemId = '';
	for(var i=0;i<sa.length;i++){
		itemId += '-'+sa[i];
	}
	itemId = itemId.substr(1);
	var menuItem = webFXTreeHandler.all[itemId];
	alert(menuItem.src);
}

function menuAction() {
    var node = tree.getSelected();
    viewCurrentNode(node);
}

function viewCurrentNode(node){
	currentUrl = node.src.split('?')[0];
	$('node_url').innerHTML = currentUrl.substr(URLPREFIX.length);
	
	ajaxRequest(currentUrl, {method:'getData'}, function(data){
		var mode = (data.length>=2 && data[0]=='{' && data[data.length-1]=='}')?'form':'text';
		$('node_data').value = data;
		switchEditMode(mode);
	});
}

function getFullPath(node) {
    var curNode = node;
    var path = '';
    while (curNode && !curNode.tree) {
        if (curNode.text != '/') {
            path = '/' + curNode.text + path;
        }
        curNode = curNode.parentNode;
    };
    return path;
}

function addZkNode(){
	var nodeName = prompt("请输入节点数据","");
	if(nodeName==null){
		return;
	}
	ajaxRequest(currentUrl, {method:'add', nodeName:nodeName}, function(){
		var node = tree.getSelected();
		node.reload();
	});
}

function delZkNode(){
	var node = tree.getSelected().parentNode;
	var ok = confirm('确定要删除节点吗：'+currentUrl);
	if(!ok){
		return;	
	}
	ajaxRequest(currentUrl, {method:'del'}, function(){
		node.reload();
	});
}

function setZkNodeData(){
	var data = prompt("请输入节点名称",$('node_data').innerHTML);
	if(data==null){
		return;
	}
	
	var node = tree.getSelected();
	ajaxRequest(currentUrl, {method:'setData',data:data}, function(){
		node.reload();
		viewCurrentNode(node);
	});
}

function saveZkNodeData(){
	var data = getEditData();
	var node = tree.getSelected();
	ajaxRequest(currentUrl, {method:'setData', 'data':data}, function(){
		node.reload();
		viewCurrentNode(node);
		alert('修改成功！');
	});
}

var tree;

function initTree(){
    webFXTreeConfig.rootIcon = "widgets/xloadtree/images/xp/folder.png";
    webFXTreeConfig.openRootIcon = "widgets/xloadtree/images/xp/openfolder.png";
    webFXTreeConfig.folderIcon = "widgets/xloadtree/images/xp/folder.png";
    webFXTreeConfig.openFolderIcon = "widgets/xloadtree/images/xp/openfolder.png";
    webFXTreeConfig.fileIcon = "widgets/xloadtree/images/xp/file.png";
    webFXTreeConfig.lMinusIcon = "widgets/xloadtree/images/xp/Lminus.png";
    webFXTreeConfig.lPlusIcon = "widgets/xloadtree/images/xp/Lplus.png";
    webFXTreeConfig.tMinusIcon = "widgets/xloadtree/images/xp/Tminus.png";
    webFXTreeConfig.tPlusIcon = "widgets/xloadtree/images/xp/Tplus.png";
    webFXTreeConfig.iIcon = "widgets/xloadtree/images/xp/I.png";
    webFXTreeConfig.lIcon = "widgets/xloadtree/images/xp/L.png";
    webFXTreeConfig.tIcon = "widgets/xloadtree/images/xp/T.png";
    webFXTreeConfig.blankIcon = "widgets/xloadtree/images/blank.png";
    webFXTreeConfig.usePersistence = false;

    var url = URLPREFIX+ROOT+"?method=getChildren";
    tree = new WebFXTree("zkmanager");
    tree.add(new WebFXLoadTreeItem(ROOT, url, "javascript:menuAction()"));

    $('treeContainer').innerHTML = tree;
}

window.addEvent('domready', function() {
	ajaxRequest('zkinfo', {}, function(data){
		ROOT = data.userRoot;
		initTree();
	});
});

</script>
<script>
function switchEditMode(mode){
	var p = $('editPanel');
	var f = $('dataEditForm');
	var e = $('node_data');
	
	var str = getEditData();
	
	if(mode=='text'){
		f.inject($('hidded'));
		p.appendChild(e);
	}else{
		e.inject($('hidded'));
		p.appendChild(f);
	}
	
	setEditData(mode, str);
}

function onBtnClick(obj){
	var action = obj.innerHTML;
	if(action=='+'){
		addRow();
	}else{
		delRow(obj);
	}
}

function addRow(){
	var ef = $('dataEditForm');
	var first = ef.getElement('dl:first-child');
	var newRow = first.clone(true);
	var btn = newRow.getElement('dt[class=button]');
	btn.set('text', '-');
	ef.grab(newRow,'bottom');
	setRowVal(newRow, '', '');
	return newRow;
}

function setRowVal(row, key, val){
	var inputs = row.getElements('input');
	inputs[0].value = key||'';
	inputs[1].value = val||'';
}

function delRow(obj){
	$(obj).getParent().dispose();
}

function setEditData(mode, data){
	if(mode=='form'){
		var json = JSON.decode(data);
		
		var rows = $('dataEditForm').getElements('dl');
		var n = -1;
		for(key in json){
			n++;
			if(n>=rows.length){
				var newRow = addRow();
				rows[n] = newRow;
			}
			setRowVal(rows[n], key, json[key]);
		}

		for(var i=rows.length-1;i>n;i--){
			rows[i].dispose();
		}
		
	}else{
		$('node_data').value = data;
	}
}

function getEditData(){
	if(getEditMode()=='text'){
		return $('node_data').value;
	}else{
		return getFormData();	
	}
}

function getEditMode(){
	if($('node_data').getParent().id!='hidded'){
		return 'text';
	}else{
		return 'form';
	}
}

function getFormData(){
	var obj = {};
	var ef = $('dataEditForm');
	var rows = ef.getElements('dl');
	for(var i=0;i<rows.length;i++){
		var row = rows[i];
		var input1 = row.getElement('input[name=key]');
		var input2 = row.getElement('input[name=val]');
		if(input1.value){
			obj[input1.value] = input2.value;
		}
	}
	var json = JSON.encode(obj);
	return json;
}

</script>
</head>
<body>

<table width="100%">
      <tr>
        <td valign="top" width="260px" style="overflow:auto">
            <div id="treeContainer"></div>
        </td>
        <td>
			<div id="mainFrame"
				style="height: 800px; border: 1px solid #DDDDDD;">
				<div id="popupMenu" style="display:; border: 1px solid #DDDDDD; background-color: #F0F0F0;">
					<a href="javascript:addZkNode();">添加节点</a> 
					<a href="javascript:delZkNode();">删除节点</a> 
					<a href="javascript:setZkNodeData();">设置节点数据</a>
					|
					修改数据:
					(<a href="javascript:switchEditMode('text');">text</a>
					<a href="javascript:switchEditMode('form');">form</a>)
					|
					<a href="javascript:saveZkNodeData();">保存节点数据</a>
				</div>
				<div><br/></div>
				<div id="mainPanel">
                    <div>
                        <span style="float:left; width:50px">
                            path:
                        </span>
                        <span id="node_url" style="float:left"></span>
                    </div>
                    <div style="clear:both">
                      <span style="float:left; width:50px">data:</span>
                      <span id="editPanel" style="float:left">
                        <textarea id="node_data" cols="60" rows="6"></textarea>
                      </span>
                    </div>
                    
			  </div>
			</div>
		</td>
  </tr>
</table>

<div id="hidded" style="display:none">

	<div id="dataEditForm" class="dtable">
		<dl>
			<dt><input name="key" /></dt>
			<dt>=</dt>
			<dd><input name="val" /></dd>
			<dt class="button" onclick="onBtnClick(this)">+</dt>
		</dl>
	</div>

</div>
</body>
</html>
